package com.java.simple.study.juc.p3.reentrant;

import com.java.simple.study.tool.Sleeper;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zhoujl
 * @date 2022/5/10 21:49
 * @desc
 */
@Slf4j(topic = "c.TestInterrupt")
public class TestInterrupt {

    static final ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
//        test1();
        test2();
    }

    public static void test2() {
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            // blocked等待锁时 不可以被打断
            lock.lock();
            try {
                log.debug("t1获得到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("主线程获取到锁");
        t1.start();
        try {
            Sleeper.sleep(1);
            //打断t1
            t1.interrupt();
            log.debug("执行打断操作");
        } finally {
            lock.unlock();
        }
    }


    public static void test1() {
        Thread t1 = new Thread(() -> {
            log.debug("启动...");
            try {
                // blocked等待锁时 可以被打断 取消等待
                lock.lockInterruptibly();
            } catch (InterruptedException e) {
                e.printStackTrace();
                log.debug("等锁过程中被打断");
                return;
            }
            try {
                log.debug("t1获得到锁");
            } finally {
                lock.unlock();
            }
        }, "t1");

        lock.lock();
        log.debug("主线程获取到锁");
        t1.start();
        try {
            Sleeper.sleep(1);
            //打断t1
            t1.interrupt();
            log.debug("执行打断操作");
        } finally {
            lock.unlock();
        }
    }

}
